﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Menu;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domian.Entities.Menu;
using B.S.BasicData.Domian.Entities.RBAC;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Menu
{
    public class UserPromissionHandler : IRequestHandler<UserPromissionCommand, ApiResult<List<RolePermisssionDTO>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IBaseRepository<RoleMenuModel> roleMenuRepo;
        private readonly IBaseRepository<UserRoleModel> userroleRepo;

        public UserPromissionHandler(IBaseRepository<MenuModel>menuRepo,IBaseRepository<RoleMenuModel>roleMenuRepo,IBaseRepository<UserRoleModel>userroleRepo)
        {
            this.menuRepo = menuRepo;
            this.roleMenuRepo = roleMenuRepo;
            this.userroleRepo = userroleRepo;
        }
        public Task<ApiResult<List<RolePermisssionDTO>>> Handle(UserPromissionCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<List<RolePermisssionDTO>>();
            res.Message = "查询成功";
            res.Code=ApiEnum.Ok;
            var list=request.RoleId.Split(',').Select(x=>Convert.ToInt64(x)).ToList();
            var menu = roleMenuRepo.GetAll();
            List<int> model=new List<int>();
            foreach (var item in list)
            {
                var mids=menu.Where(x=>x.Rid==item).Select(x=>x.Mid).ToList();
                model.AddRange(mids);
            }
            var menusQuery = menuRepo.GetAll().Where(x => !x.IsDel);
            var data =find(0, menusQuery.ToList(), model);
            res.Data = data;
            return Task.FromResult(res);
        }

        public List<RolePermisssionDTO> find(int id, List<MenuModel> ids, List<int> mid)
        {
            var res=ids.Where(x=>x.Pid==id &&mid.Contains(x.Id)).ToList();
            List<RolePermisssionDTO>list=new List<RolePermisssionDTO>();
            foreach (var item in res)
            {
                list.Add(new RolePermisssionDTO()
                {
                    MenuName = item.MenuName,
                    Url= item.Url,
                    Children=find(item.Id, ids, mid)
                });
            }
            return list;
        }
    }
}
